#include "triangle.h"
#include "line.h"

#include <algorithm>

Triangle::Triangle()
{
}

Triangle::Triangle(Point p0, Point p1, Point p2)
{
    vertex[0] = p0;
    vertex[1] = p1;
    vertex[2] = p2;
}

bool Triangle::ptIn(const Point &pt)
{
    Vector v0 = vertex[2] - vertex[0] ;
    Vector v1 = vertex[1] - vertex[0] ;
    Vector v2 = pt - vertex[0] ;

    double dot00 = v0.dot(v0) ;
    double dot01 = v0.dot(v1) ;
    double dot02 = v0.dot(v2) ;
    double dot11 = v1.dot(v1) ;
    double dot12 = v1.dot(v2) ;

    double inverDeno = 1 / (dot00 * dot11 - dot01 * dot01) ;

    double u = (dot11 * dot02 - dot01 * dot12) * inverDeno ;
    if (u < 0 || u > 1) // if u out of range, return directly
    {
        return false ;
    }

    float v = (dot00 * dot12 - dot01 * dot02) * inverDeno ;
    if (v < 0 || v > 1) // if v out of range, return directly
    {
        return false ;
    }

    return u + v <= 1 ;
}

double Triangle::distance(const Point &pt)
{
    Line l0(vertex[0], vertex[1]);
    Line l1(vertex[1], vertex[2]);
    Line l2(vertex[0], vertex[2]);

    double dis = std::min(l0.distance(pt, true),
                          std::min(l1.distance(pt, true), l2.distance(pt, true)));
    if (ptIn(pt))
    {
        return -dis;
    }
    else
    {
        return dis;
    }
}

void Triangle::draw()
{
}
